//
//  MGYAlertView.m
//  MGYRightAndError
//
//  Created by jiangjunwy on 16/7/13.
//  Copyright © 2016年 SanYouApp. All rights reserved.
//

#import "MGYAlertView.h"
#import "LoadingView.h"

@implementation MGYAlertView{
    UIView      *_backView;
    UIView      *_alertview;
    UILabel     *_promptLable;
    BOOL        _isShow;
    LoadingView *timerView;
    CAShapeLayer *shapeLayer;
}

- (void)dealloc {
    _backView                   = nil;
}

static const CGFloat Raduis = 40.0f;
static const CGFloat lineWidth = 50.0f;
static const CGFloat lineRightHeight = 5.0f;
static const CGFloat lineHeight = 3.0f;

static const CGFloat kStep1Duration = 0.2;
static const CGFloat kStep2Duration = 0.5;
static const CGFloat kStep3Duration = 4.5;
static const CGFloat kStep4Duration = 0.15;

static const CGFloat kALERTW = 270;
static const CGFloat kALERTH = 160;

#define kTopY       Raduis - lineGapHeight
#define kCenterY   CGRectGetMidY(_backView.frame)-20
#define kBottomY    kCenterY + lineGapHeight + lineHeight
#define Radians(x)  (M_PI * (x) / 180.0)



- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
    }
    return self;
}



+ (MGYAlertView *) sharedInstance{

    static MGYAlertView *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[MGYAlertView alloc] initWithWaitingData];
    });
    return instance;
}

- (instancetype)initWithWaitingData{
    
    self = [self init];
    
    if (self) {
        _backView = [[UIView alloc] initWithFrame:self.frame];
        _backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
        _backView.alpha = 0.0f;
        [self addSubview:_backView];
        
        _alertview = [[UIView alloc]init];
        _alertview.backgroundColor = [UIColor whiteColor];
        [self addSubview:_alertview];
        
        _alertview.frame = CGRectMake(CGRectGetMidX(_backView.frame)-kALERTW/2, CGRectGetMidY(_backView.frame)-kALERTH/2, kALERTW, kALERTH);
        _alertview.layer.cornerRadius = 5.0f;
        _alertview.layer.masksToBounds = YES;
        _alertview.alpha = 0.0;
        
        _promptLable  =[[ UILabel alloc]initWithFrame:CGRectMake(0, kALERTH-50, kALERTW, 50)];
        _promptLable.textAlignment = NSTextAlignmentCenter;
        _promptLable.textColor = [UIColor orangeColor];
        [_alertview addSubview:_promptLable];
        
    }
    
    return self;
}

/**
 *  loading外部调用API
 *
 *  @param title 标题
 */
+ (void)MGYShowLoadingWithText:(nullable NSString *)title;{
    [[MGYAlertView sharedInstance] showLoadingWith:title];
}
/**
 *  加载成功外部调用API
 *
 *  @param title 标题
 */
+ (void)MGYSuccessWithText:(nullable NSString *)title;{
    
    [[MGYAlertView sharedInstance] showSuccessWith:title];
}
/**
 *  加载失败外部调用API
 *
 *  @param title 标题
 */
+ (void)MGYfailureWithText:(nullable NSString *)title;{
    [[MGYAlertView sharedInstance] showErrorWith:title];
}

/**
 *  移除弹窗
 */
+ (void)MGYDisappearFromPage;{
    [[MGYAlertView sharedInstance] dismiss];
}
- (void)dismiss
{
    _isShow = NO;
    [self removeAllBlueLayer];
    [UIView animateWithDuration:0.35 animations:^{
        _backView.alpha = 0.0;
        _alertview.alpha = 0.0;
        [self makeAllTransparent];
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        [self removeAllBlueLayer];
    }];
}

-(void)showLoadingWith:(NSString *)title{
    [[[[UIApplication sharedApplication] delegate] window] addSubview:self];
    [self removeAllBlueLayer];
     [UIView animateWithDuration:0.25 animations:^{
        
        _backView.alpha = 1.0;
        _alertview.alpha = 1,0;
        _promptLable.text = title;
        
     } completion:^(BOOL finished) {
        [self waitAnimationStep];
     }];
}
-(void)showErrorWith:(NSString *)title{
    
    [[[[UIApplication sharedApplication] delegate] window] addSubview:self];
    [self removeAllBlueLayer];
     [UIView animateWithDuration:0.25 animations:^{
        _backView.alpha = 1.0;
        _alertview.alpha = 1.0;
        _promptLable.text = title;
        
     } completion:^(BOOL finished) {
         [self startAnimationError];
     }];

}

-(void)showSuccessWith:(NSString *)title{
    [[[[UIApplication sharedApplication] delegate] window] addSubview:self];
    [self removeAllBlueLayer];
    [UIView animateWithDuration:0.25 animations:^{
        _backView.alpha = 1.0;
        _alertview .alpha = 1.0;
        _promptLable.text = title;
        
    } completion:^(BOOL finished) {
//        [self startAnimationSuccess];
        
        [self LoadingAnimationStep];
    }];

}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:_backView];
    if (!CGRectContainsPoint([_alertview frame], point)) {
        [self dismiss];
    }
}



-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
//    [_changedLayer removeFromSuperlayer];
//    [_rightLayer removeFromSuperlayer];
    
    if ([[anim valueForKey:@"animationNameSuccess"] isEqualToString:@"animationStepSuccess"]) {
        /**
         *  圆形动画完成  如果_Bsuccess == 1则开始画对号  否则画❌
         */
        if (_Bsuccess) {
            [self animationStep2];
        }else{
            [self errorAnimationStep1];
        }
        
        
    }else if ([[anim valueForKey:@"errorAnimationName1"] isEqualToString:@"errorAnimationStep1"]){
        /**
         *  错误❌d的第一条线完成   开始第二条
         */
        [self errorAnimationStep2];
    }else if ([[anim valueForKey:@"waitanimationName"] isEqualToString:@"waitanimationStep"]){
       
    }else if ([[anim valueForKey:@"animationNameSuccess1"] isEqualToString:@"animationStepSuccess1"]){
        [self LoadingAnimationStep2];
    }
    
    
    
}


-(void)removeAllBlueLayer{
    [_LoadingLayer removeFromSuperlayer];
    [_changedLayer removeFromSuperlayer];
    [_rightLayer removeFromSuperlayer];
    [timerView removeFromSuperview];
    [_errorLayer1 removeFromSuperlayer];
    [_errorLayer2 removeFromSuperlayer];
    
}
-(void)makeAllTransparent{
    _changedLayer.opacity = 0;
    _rightLayer.opacity = 0;
    timerView.alpha = 0;
    _errorLayer1.opacity = 0;
    _errorLayer2.opacity = 0;
}

-(void)startAnimationSuccess;{
    _Bsuccess = YES;
    [self animationStep1];
}

-(void)startAnimationError;{
    
    [self removeAllBlueLayer];
    _Bsuccess = NO;
    [self animationStep1];
    
}

-(void)startAnimation3;{
    
    [self removeAllBlueLayer];
    [self waitAnimationStep];
}





/**
 *  画圆动画
 */
- (void) animationStep1{
    _changedLayer = [CAShapeLayer layer];
    _changedLayer.fillColor = [UIColor clearColor].CGColor;
    _changedLayer.strokeColor = [UIColor colorWithRed:0.000 green:0.706 blue:0.176 alpha:1.000].CGColor;
    _changedLayer.contentsScale = [UIScreen mainScreen].scale;
    _changedLayer.lineWidth = lineHeight ;
    _changedLayer.lineCap = kCALineCapRound;
    [self.layer addSublayer:_changedLayer];
    
    
    
    //30度,经过反复测试，效果最好
    CGFloat angle = Radians(0);

    
    //组合path 路径
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.center.x,kCenterY)
                                                         radius:Raduis
                                                     startAngle:2 * M_PI - angle
                                                       endAngle:M_PI + angle
                                                      clockwise:NO];
    //    [path1 appendPath:path1];
    
    UIBezierPath *path1 = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.center.x,kCenterY)
                                                         radius:Raduis
                                                     startAngle:M_PI *3/2 - (M_PI_2 -angle)
                                                       endAngle:-M_PI_2 - (M_PI_2 -angle)
                                                      clockwise:NO];
    
    
    [path appendPath:path1];
    
    _changedLayer.path = path.CGPath;
    
    
    
    CGFloat orignPercent = [self calculateCurveLength] / [self calculateTotalLength];
    CGFloat endPercent =([self calculateCurveLength] + Radians(120) *Raduis ) / [self calculateTotalLength];
    
    _changedLayer.strokeStart = endPercent;
    
    CAKeyframeAnimation *startAnimation = [CAKeyframeAnimation animationWithKeyPath:@"strokeStart"];
    startAnimation.values = @[@0.0,@(endPercent)];
    
    CAKeyframeAnimation *EndAnimation = [CAKeyframeAnimation animationWithKeyPath:@"strokeEnd"];
    EndAnimation.values = @[@(orignPercent),@1.0];
    
    
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = [NSArray arrayWithObjects:startAnimation,EndAnimation, nil];
    animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    animationGroup.duration = kStep3Duration;
    animationGroup.delegate = self;
    animationGroup.removedOnCompletion = YES;
    [animationGroup setValue:@"animationStepSuccess" forKey:@"animationNameSuccess"];
    
    [_changedLayer addAnimation:animationGroup forKey:nil];
}

#pragma mark  ------------------------出现对号的动画----------------------------
/**
 *  出现对号的动画
 */
- (void) animationStep2{
    _rightLayer = [CAShapeLayer layer];
    _rightLayer.fillColor = [UIColor clearColor].CGColor;
    _rightLayer.strokeColor = [UIColor colorWithRed:0.000 green:0.706 blue:0.176 alpha:1.000].CGColor;
    _rightLayer.contentsScale = [UIScreen mainScreen].scale;
    _rightLayer.lineWidth = lineRightHeight ;
    _rightLayer.lineCap = kCALineCapRound;
    [self.layer addSublayer:_rightLayer];
    
    
    // path
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    path.lineCapStyle = kCGLineCapSquare; //线条拐角
    path.lineJoinStyle = kCGLineCapRound; //终点处理
    
    [path moveToPoint:CGPointMake(CGRectGetMidX(self.bounds) - Raduis + 20, kCenterY)];
    [path addLineToPoint:CGPointMake(CGRectGetMidX(self.bounds) - Raduis / 6, kCenterY + Raduis / 6 * 2)];
    [path addLineToPoint:CGPointMake(CGRectGetMidX(self.bounds) + Raduis - Raduis / 7 * 3, kCenterY - Raduis / 2 +10)];
    
    self.rightLayer.path = path.CGPath;
    
    //SS(strokeStart)
    CGFloat SSFrom = 0;
    CGFloat SSTo = 1.0;
    // animation
    CABasicAnimation *startAnimation = [CABasicAnimation animationWithKeyPath:@"strokeStart"];
    startAnimation.fromValue = @(SSFrom);
    startAnimation.toValue = @(SSTo);
    
    CABasicAnimation *endAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    endAnimation.fromValue = @(SSFrom);
    endAnimation.toValue = @(SSTo);
    
    
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = @[endAnimation];
    animationGroup.duration = kStep2Duration;
    animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    animationGroup.delegate = self;
    animationGroup.removedOnCompletion = YES;
    [animationGroup setValue:@"animationStep2" forKey:@"animationName2"];
    
    [self.rightLayer addAnimation:animationGroup forKey:nil];
}


#pragma mark  ------------------------出现X的动画第一步----------------------------
/**
 *  出现X的动画第一步
 */
- (void) errorAnimationStep1{
    _errorLayer1 = [CAShapeLayer layer];
    _errorLayer1.fillColor = [UIColor clearColor].CGColor;
    _errorLayer1.strokeColor = [UIColor colorWithRed:0.000 green:0.706 blue:0.176 alpha:1.000].CGColor;
    _errorLayer1.contentsScale = [UIScreen mainScreen].scale;
    _errorLayer1.lineWidth = lineRightHeight ;
    _errorLayer1.lineCap = kCALineCapRound;
    [self.layer addSublayer:_errorLayer1];
    
    
    // path
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    path.lineCapStyle = kCGLineCapRound; //线条拐角
    path.lineJoinStyle = kCGLineCapRound; //终点处理
    
    [path moveToPoint:CGPointMake(CGRectGetMidX(self.bounds) - Raduis/3, kCenterY-Raduis/3)];
    [path addLineToPoint:CGPointMake(CGRectGetMidX(self.bounds) + Raduis / 3, kCenterY + Raduis / 3)];
    
    self.errorLayer1.path = path.CGPath;
    
    //SS(strokeStart)
    CGFloat SSFrom = 0;
    CGFloat SSTo = 1.0;
    // animation
    CABasicAnimation *startAnimation = [CABasicAnimation animationWithKeyPath:@"strokeStart"];
    startAnimation.fromValue = @(SSFrom);
    startAnimation.toValue = @(SSTo);
    
    CABasicAnimation *endAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    endAnimation.fromValue = @(SSFrom);
    endAnimation.toValue = @(SSTo);
    
    
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = @[endAnimation];
    animationGroup.duration = kStep1Duration;
    animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    animationGroup.delegate = self;
    animationGroup.removedOnCompletion = YES;
    [animationGroup setValue:@"errorAnimationStep1" forKey:@"errorAnimationName1"];
    
    [self.errorLayer1 addAnimation:animationGroup forKey:nil];
}

#pragma mark  ------------------------出现X的动画第二步----------------------------
/**
 *  出现X的动画第二步
 */
- (void) errorAnimationStep2{
    _errorLayer2 = [CAShapeLayer layer];
    _errorLayer2.fillColor = [UIColor clearColor].CGColor;
    _errorLayer2.strokeColor = [UIColor colorWithRed:0.000 green:0.706 blue:0.176 alpha:1.000].CGColor;
    _errorLayer2.contentsScale = [UIScreen mainScreen].scale;
    _errorLayer2.lineWidth = lineRightHeight ;
    _errorLayer2.lineCap = kCALineCapRound;
    [self.layer addSublayer:_errorLayer2];
    
    
    // path
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    path.lineCapStyle = kCGLineCapRound; //线条拐角
    path.lineJoinStyle = kCGLineCapRound; //终点处理
    
    [path moveToPoint:CGPointMake(CGRectGetMidX(self.bounds) + Raduis/3, kCenterY-Raduis/3)];
    [path addLineToPoint:CGPointMake(CGRectGetMidX(self.bounds) - Raduis / 3, kCenterY + Raduis / 3)];
    
    self.errorLayer2.path = path.CGPath;
    
    //SS(strokeStart)
    CGFloat SSFrom = 0;
    CGFloat SSTo = 1.0;
    // animation
    CABasicAnimation *startAnimation = [CABasicAnimation animationWithKeyPath:@"strokeStart"];
    startAnimation.fromValue = @(SSFrom);
    startAnimation.toValue = @(SSTo);
    
    CABasicAnimation *endAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    endAnimation.fromValue = @(SSFrom);
    endAnimation.toValue = @(SSTo);
    
    
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = @[endAnimation];
    animationGroup.duration = kStep1Duration;
    animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    animationGroup.delegate = self;
    animationGroup.removedOnCompletion = YES;
    [animationGroup setValue:@"errorAnimationStep2" forKey:@"errorAnimationName2"];
    
    [self.errorLayer2 addAnimation:animationGroup forKey:nil];
}




/**
 *  等待动画
 */
- (void) waitAnimationStep{
    
    CGRect frame = CGRectMake(self.center.x-Raduis, kCenterY-Raduis, Raduis*2, Raduis*2);
    
    timerView = [[LoadingView alloc] initWithFrame:frame arcWidth:lineHeight current:1 total:4];
    timerView.backgroundColor=[UIColor whiteColor];//设置背景色：白色
    [self addSubview: timerView];
    
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    
        // 绕着(0, 0, 1)这个向量轴 Z 轴，顺时针旋转45°(M_PI_4)
    rotationAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(-M_PI_2, 0,0, 1)];
    rotationAnimation.duration = kStep4Duration;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    [timerView.layer addAnimation:rotationAnimation forKey:nil];
    
}




-(CGFloat)calculateTotalLength
{
    
    CGFloat curveLength = [self calculateCurveLength];
    //一个圆 + 120度弧长的 总长度
    CGFloat length = (Radians(120) + 2 * M_PI) * Raduis;
    CGFloat totalLength = curveLength + length;
    
    return totalLength;
}

-(CGFloat)calculateCurveLength{
    
    CGFloat angle = Radians(30);
    
    CGFloat endPointX = self.center.x + Raduis * cos(angle);
    CGFloat endPointY = kCenterY - Raduis * sin(angle);
    
    CGFloat startPointX = self.center.x + lineWidth/2.0;
    CGFloat startPointY = kCenterY;
    
    CGFloat controlPointX = self.center.x + Raduis *acos(angle);
    CGFloat controlPointY = kCenterY;
    
    CGFloat curveLength = [self bezierCurveLengthFromStartPoint:CGPointMake(startPointX, startPointY)
                                                     toEndPoint:CGPointMake(endPointX,endPointY)
                                               withControlPoint:CGPointMake(controlPointX, controlPointY)];
    
    return curveLength;
}

//求贝塞尔曲线长度
-(CGFloat) bezierCurveLengthFromStartPoint:(CGPoint)start toEndPoint:(CGPoint) end withControlPoint:(CGPoint) control
{
    const int kSubdivisions = 50;
    const float step = 1.0f/(float)kSubdivisions;
    
    float totalLength = 0.0f;
    CGPoint prevPoint = start;
    
    // starting from i = 1, since for i = 0 calulated point is equal to start point
    for (int i = 1; i <= kSubdivisions; i++)
    {
        float t = i*step;
        
        float x = (1.0 - t)*(1.0 - t)*start.x + 2.0*(1.0 - t)*t*control.x + t*t*end.x;
        float y = (1.0 - t)*(1.0 - t)*start.y + 2.0*(1.0 - t)*t*control.y + t*t*end.y;
        
        CGPoint diff = CGPointMake(x - prevPoint.x, y - prevPoint.y);
        
        totalLength += sqrtf(diff.x*diff.x + diff.y*diff.y); // Pythagorean
        
        prevPoint = CGPointMake(x, y);
    }
    
    return totalLength;
}






#pragma mark  ------------------------22222----------------------------

/**
 *  画圆动画
 */
- (void) LoadingAnimationStep{
    _LoadingLayer = [CAShapeLayer layer];
    _LoadingLayer.fillColor = [UIColor clearColor].CGColor;
    _LoadingLayer.strokeColor = [UIColor colorWithRed:0.000 green:0.706 blue:0.176 alpha:1.000].CGColor;
    _LoadingLayer.contentsScale = [UIScreen mainScreen].scale;
    _LoadingLayer.lineWidth = lineHeight ;
    _LoadingLayer.lineCap = kCALineCapRound;
    [self.layer addSublayer:_LoadingLayer];

    
    
    //组合path 路径
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.center.x,kCenterY)
                                                        radius:Raduis
                                                    startAngle:0
                                                      endAngle:M_PI
                                                     clockwise:NO];
    //    [path1 appendPath:path1];
    
//    UIBezierPath *path1 = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.center.x,kCenterY)
//                                                         radius:Raduis
//                                                     startAngle:M_PI *3/2 - (M_PI_2)
//                                                       endAngle:-M_PI_2 - (M_PI_2)
//                                                      clockwise:NO];
//    
//    
//    [path appendPath:path1];
    
    _LoadingLayer.path = path.CGPath;
    
    
    CGFloat orignPercent = [self calculateCurveLength] / [self calculateTotalLength];
    CGFloat endPercent =([self calculateCurveLength] + Radians(120) *Raduis ) / [self calculateTotalLength];
    
    _LoadingLayer.strokeStart = 0.0;
    
    CAKeyframeAnimation *startAnimation = [CAKeyframeAnimation animationWithKeyPath:@"strokeStart"];
    startAnimation.values = @[@0.0,@0.25];
    
    CAKeyframeAnimation *EndAnimation = [CAKeyframeAnimation animationWithKeyPath:@"strokeEnd"];
    EndAnimation.values = @[@(orignPercent),@1.0];
    
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = [NSArray arrayWithObjects:startAnimation,EndAnimation, nil];
    animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    animationGroup.duration = 0.5;
    animationGroup.delegate = self;
    animationGroup.removedOnCompletion = YES;
    [animationGroup setValue:@"animationStepSuccess1" forKey:@"animationNameSuccess1"];
    
    [_LoadingLayer addAnimation:animationGroup forKey:nil];
    
}

- (void) LoadingAnimationStep2{
    //组合path 路径
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.center.x,kCenterY)
                                                        radius:Raduis
                                                    startAngle:M_PI_2+M_PI+M_PI_4
                                                      endAngle:2*M_PI
                                                     clockwise:NO];
    
    _LoadingLayer.path = path.CGPath;
    
    CAKeyframeAnimation *startAnimation = [CAKeyframeAnimation animationWithKeyPath:@"strokeStart"];
    startAnimation.values = @[@0.0,@1.0];
    
    CAKeyframeAnimation *EndAnimation = [CAKeyframeAnimation animationWithKeyPath:@"strokeEnd"];
    EndAnimation.values = @[@0.5,@1.0];
    
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = [NSArray arrayWithObjects:startAnimation,EndAnimation, nil];
    animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    animationGroup.duration = 0.8;
    animationGroup.delegate = self;
    animationGroup.removedOnCompletion = YES;
    [animationGroup setValue:@"animationStepSuccess22" forKey:@"animationNameSuccess22"];
    
    [_LoadingLayer addAnimation:animationGroup forKey:nil];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
